import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Typography, Descriptions, Tag, message, Row, Col } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';

import { fetchTode } from '../services/todo';
import type { Todo } from '../services/todo';

const { Title, Text } = Typography;

const TodoDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [todo, setTodo] = useState<Todo | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchTodoDetail = async () => {
      if (!id) return;

      try {
        setLoading(true);
        const data = await fetchTode(parseInt(id));
        setTodo(data);
      } catch (error) {
        message.error('加载待办事项详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchTodoDetail();
  }, [id]);

  return (
    <div>
      <Button type="text" icon={<ArrowLeftOutlined />} onClick={() => navigate('/')} style={{ marginBottom: 16 }}>
        返回列表
      </Button>

      <Card title="待办事项详情" loading={loading} className="todo-detail-card">
        {todo ? (
          <Descriptions bordered column={1}>
            <Descriptions.Item label="ID">
              <Text strong>{todo.id}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="标题">
              <Text>{todo.title}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="用户ID">
              <Text>{todo.userId}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={todo.completed ? 'success' : 'warning'}>
                {todo.completed ? '已完成' : '未完成'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              <Text type="secondary">2023-06-15 10:30:00</Text>
            </Descriptions.Item>
            <Descriptions.Item label="最后更新">
              <Text type="secondary">2023-06-16 14:45:00</Text>
            </Descriptions.Item>
          </Descriptions>
        ) : (
          !loading && (
            <div style={{ textAlign: 'center', padding: 24 }}>
              <Title level={4}>未找到待办事项</Title>
              <Text type="secondary">ID 为 {id} 的待办事项不存在</Text>
              <div style={{ marginTop: 16 }}>
                <Button type="primary" onClick={() => navigate('/')}>
                  返回列表
                </Button>
              </div>
            </div>
          )
        )}

        <Row justify="end" style={{ marginTop: 24 }}>
          <Col>
            <Button type="primary" onClick={() => navigate(`/todo/${id}/edit`)} style={{ marginRight: 8 }}>
              编辑
            </Button>
            <Button danger>删除</Button>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default TodoDetailPage;